package com.gouda.core.dao;

import com.google.common.collect.Maps;
import com.gouda.core.entity.AdvertisementTypeEntity;
import com.gouda.core.enums.PlatformEnum;
import com.gouda.core.utils.CacheKey;
import com.hephaestus.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.amethyst.atlas.db.MagicDao;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by souu on 15/12/5.
 */
@Slf4j
@Repository
public class AdvertisementTypeDao extends MagicDao {

    private static final String BASE_SQL_ID = "select id from advertisement_type";

    public AdvertisementTypeEntity getAdvertisementTypeByAdId(long adId, PlatformEnum platform) {
        if (adId <= 0) {
            return null;
        }
        Long id = (Long) CacheUtil.getInstance().get(CacheKey.getAdvertisementTypeByAdId(adId, platform));
        if (id == null || id.longValue() <= 0) {
            StringBuilder sql = new StringBuilder("");
            sql.append(BASE_SQL_ID);
            sql.append(" where ad_id = :adId");
            Map<String, Object> param = Maps.newHashMap();
            param.put("adId", adId);
            if (platform != null) {
                sql.append(" and platform = :platform");
                param.put("platform", platform.getCode());
            }
            List<Long> ids = this.listColumns(AdvertisementTypeEntity.class, sql.toString(), param, Long.class);
            if (CollectionUtils.isEmpty(ids)) {
                return null;
            }
            id = ids.get(0);
            try {
                CacheUtil.getInstance().add(CacheKey.getAdvertisementTypeByAdId(adId, platform), id);
            } catch (InterruptedException e) {
                log.error("getAdvertisementTypeByAdId cache error:{}", e.getMessage());
            }
        }

        return this.unique(AdvertisementTypeEntity.class, id);
    }
}
